# SPDX-License-Identifier: Apache-2.0

# Create folder for autoconfig.h
set(AUTOGEN_KCONFIG ${AUTOGEN_DIR})
file(MAKE_DIRECTORY ${AUTOGEN_KCONFIG})

if(${BOARD})
    set(BOARD_DEFCONFIG ${BOARD_DIR}/${BOARD}_defconfig)
else()
    set(BOARD_DEFCONFIG ${BOARD_DIR}/defconfig)
endif()

set(kconfig_top    ${PROJECT_ROOT}/Kconfig)
set(kconfig_header ${AUTOGEN_KCONFIG}/autoconfig.h)
set(kconfig_out    ${BUILD_DIR}/.config)
set(kconfig_list   ${AUTOGEN_KCONFIG}/sources.txt)

# Re-configure (Re-execute all CMakeLists.txt code) when autoconfig.h/.config changes
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${kconfig_header})

if(EXISTS ${kconfig_out})
    set(kconfig_input ${kconfig_out})
else()
    set(kconfig_handwritten_input --handwritten-input-configs)
    set(kconfig_input ${BOARD_DEFCONFIG})
endif()

# Target menuconfig
add_custom_target(
    menuconfig
    ${CMAKE_COMMAND} -E env
    PYTHON_EXECUTABLE=${Python_EXECUTABLE}
    KCONFIG_CONFIG=${kconfig_out}
    ARCH=$ENV{ARCH}
    CMAKE_BINARY_DIR=$ENV{CMAKE_BINARY_DIR}
    ${Python_EXECUTABLE}
    ${PROJECT_ROOT}/scripts/kconfig/menuconfig.py 
    ${kconfig_top}
    WORKING_DIRECTORY ${PROJECT_ROOT}
    USES_TERMINAL
)

# Generate autoconfig.h
execute_process(
    COMMAND
    ${Python_EXECUTABLE}
    ${PROJECT_ROOT}/scripts/kconfig/kconfig.py
    ${kconfig_handwritten_input}
    ${kconfig_top}
    ${kconfig_out}
    ${kconfig_header}
    ${kconfig_list}
    ${kconfig_input}
    WORKING_DIRECTORY ${PROJECT_ROOT}
    RESULT_VARIABLE ret
)

set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${kconfig_out})

kconfig_import(CONFIG_ ${kconfig_out})